/*
 *
 *  * | Licensed 未经许可不能去掉「OPENIITA」相关版权
 *  * +----------------------------------------------------------------------
 *  * | Author: xw2sy@163.com
 *  * +----------------------------------------------------------------------
 *
 *  Copyright [2024] [OPENIITA]
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * /
 */
package cc.iotkit.ruleengine.action.group;

import cc.iotkit.common.exception.BizException;
import cc.iotkit.common.thing.DeviceService;
import cc.iotkit.common.thing.ThingModelMessage;
import cc.iotkit.common.thing.ThingService;
import cc.iotkit.common.utils.UniqueIdUtil;
import cc.iotkit.data.manager.IDeviceGroupData;
import cc.iotkit.model.device.DeviceInfo;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import static cc.iotkit.common.enums.ErrCode.DEVICE_NOT_FOUND;
import static cc.iotkit.common.enums.ErrCode.GROUP_NOT_FOUND;

@Component
public class GroupActionService {

    @Autowired
    private DeviceService deviceService;
    @Autowired
    private IDeviceGroupData deviceGroupData;

    public String invoke(GroupService service) {
        String pk = service.getGroup().split("/")[0];
        String groupId = service.getGroup().split("/")[1];
        String groupConfig = deviceGroupData.findGroupConfigByGroupId(groupId);
        if (StrUtil.isEmpty(groupConfig)) {
            throw new BizException(GROUP_NOT_FOUND);
        }
        List<DeviceInfo> devices = deviceGroupData.findDevicesByGroupId(groupId);
        if (CollUtil.isEmpty(devices) || !pk.equals(devices.get(0).getProductKey())) {
            throw new BizException(DEVICE_NOT_FOUND);
        }
        // 群控设备
        DeviceInfo device = null;
        for (DeviceInfo d : devices) {
            if (d.getState().isOnline()) {
                device = d;
            }
        }
        device = device == null ? devices.get(0) : device;

        // 微自然单灯用轮询群控设备
        if (device.getProductKey().equalsIgnoreCase("hATm2Tswh3TDik8W")) {
            ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
            try {
                AtomicInteger index = new AtomicInteger(0);
                for (DeviceInfo dev : devices) {
                    if (!dev.getState().isOnline()) {
                        // log.info("群控中, 设备{}离线", device.getDeviceName());
                        continue;
                    }
                    // 微自然单灯控制需要传父设备mac地址
                    Map<String, Object> data = service.parseInputData();
                    data.put("gwmac", dev.getParentId());

                    ThingService<Map<String, Object>> thingService = new ThingService<>();
                    thingService.setMid(UniqueIdUtil.newRequestId());
                    thingService.setProductKey(dev.getProductKey());
                    thingService.setDeviceName(dev.getDeviceName());
                    thingService.setType(ThingModelMessage.TYPE_PROPERTY);
                    thingService.setIdentifier(service.getIdentifier());
                    thingService.setParams(data);
                    scheduler.schedule(() -> {
                        // 串行1秒调度
                        deviceService.invoke(thingService);
                    }, index.getAndIncrement(), TimeUnit.SECONDS);
                }
            } finally {
                scheduler.shutdown(); // 防止资源泄露
            }
            return UniqueIdUtil.newRequestId();
        }

        ThingService<Map<String, Object>> thingService = new ThingService<>();
        thingService.setMid(UniqueIdUtil.newRequestId());
        thingService.setProductKey(device.getProductKey());
        thingService.setDeviceName(device.getDeviceName());
        thingService.setType(service.getType());
        thingService.setIdentifier(service.getIdentifier());
        thingService.setGroupConfig(groupConfig);
        thingService.setParams(service.parseInputData());
        deviceService.invoke(thingService);
        return thingService.getMid();
    }

    @Data
    public static class GroupService {

        private String group;

        private String identifier;

        private String type;

        public String getType() {
            //identifier为set固定为群组属性设置，其它暂时也为群组属性设置
            if (ThingModelMessage.ID_PROPERTY_SET.equals(identifier) ||
                    ThingModelMessage.ID_PROPERTY_GET.equals(identifier)) {
                return ThingModelMessage.TYPE_GROUP_PROPERTY;
            }
            return ThingModelMessage.TYPE_GROUP_PROPERTY;
        }

        private List<Parameter> inputData;

        public Map<String, Object> parseInputData() {
            Map<String, Object> data = new HashMap<>();
            for (Parameter p : inputData) {
                data.put(p.getIdentifier(), p.getValue());
            }
            return data;
        }

        @Data
        public static class Parameter {
            private String identifier;
            private Object value;
        }
    }

}
